/**
 * @author klv
 */
if(typeof QS_ScreenerList=="undefined"){
    QS_ScreenerList={};//{"51":[{id:***,title:****,type:****}]}
}

var QS_SearchDB=function(type){
    this.URL='../template.jsp';
    this.config={maxList:5};
	this.ready=false;
    this.type=type;//user custom search list
};
QS_SearchDB.prototype = {
    getSearchData: function(id, callback){
        var item=this._getScreenerItem(id);
        if (!item.data) {
            var self = this;
            DBHelper.getWidgetTemplate(id, function(d){
                var obj = null;
                if ($.trim(d) != '') {
                    obj = $.evalJSON(d);
                    self._setSearchData(id,obj);
                }
                if (typeof callback == 'function') {
                    callback(obj);
                }
            });
        }
        else {
            if (typeof callback == 'function') {
                callback(item.data);
            }
        }
        return item.data;
    },
    _setSearchData:function(id,data){
        for(var i=0,l=QS_ScreenerList[this.type].length;i<l;i++){
            if(QS_ScreenerList[this.type][i].id==id){
                QS_ScreenerList[this.type][i].data=data;
            }
        }
    },
    _getScreenerItem:function(id){
        for(var i=0,l=QS_ScreenerList[this.type].length;i<l;i++){
            if(QS_ScreenerList[this.type][i].id==id){
                return QS_ScreenerList[this.type][i];
            }
        }
        return {};
    },
    getSearchNameByID: function(id){
		return this._getScreenerItem(id).title;
    },
	getSearchIDByName: function(name){
        for (var i = 0, l = QS_ScreenerList[this.type].length; i < l; i++) {
            var temp = QS_ScreenerList[this.type][i];
            if (temp.title == name) {
                return temp.id;
            }
        }
        return "";
    },
    existName:function(name){
        for (var i = 0, l = QS_ScreenerList[this.type].length; i < l; i++) {
            var temp=QS_ScreenerList[this.type][i];
            if(temp.title==name){
                return true;
            }
        }
        return false;
    },
    getSearchMenuData:function(){
        var namelist=[];
        for(var i=0,l=QS_ScreenerList[this.type].length;i<l;i++){
            if(i>this.config.maxList){
                namelist.push({
                    txt:'More...',
                    val:'mor',
                    cmd:'mor',
                    selectable: true
                });
                break;
            }
            var temp=QS_ScreenerList[this.type][i];
            namelist.push({
                txt:temp.title,
                val:temp.id,
                selectable: false,
                subMenu:[
                    {txt: "Select",
                     val: temp.id,
                     cmd: "sel",
                     selectable: true
                    },
                    {txt: "Delete",
                     val: temp.id,
                     cmd: "del",
                     selectable: true
                    }
                ]
            });
        }
        return namelist;
    },
    getSearchNameList: function(callback){
        if(!QS_ScreenerList[this.type]){ QS_ScreenerList[this.type]=[];}
        if (QS_ScreenerList[this.type].length==0) {
            var self = this;
            DBHelper.getWidgetTemplateListByType(this.type, function(d){
                if (d == "") {
                    return;
				}
                d = $.evalJSON(d);
                QS_ScreenerList[self.type] = d.temp;
                if (callback) {
                    if(d.errorMessage!=''){
                        callback("error");
                    }else{
                        callback(QS_ScreenerList[self.type]);
                    }
                }
            });
        }
        else {
            if (callback) {
                callback(QS_ScreenerList[this.type]);
            }
        }
    },
    deleteSearchItem: function(id, callback){
        var self=this;
        DBHelper.deleteWidgetTemplate(id, function(d){
            if (d) {
                var temp = QS_ScreenerList[self.type];
                for (var i = 0, l = temp.length; i < l; i++) {
                    if (temp[i].id == id) {
                        temp.splice(i, 1);
                        break;
                    }
                }
            }
            if (typeof callback == 'function') {
                    callback(d);
            }
        });
    },
    updateSearchItem: function(id, searchData, callback){
        var self = this;
        DBHelper.saveWidgetTemplate(id, searchData, function(d){
            if (d) {
                self._setSearchData(id,searchData);
            }
            if (typeof callback == 'function') {
                callback(d);
            }
        });
    },
    addSearchItem: function(name, searchllist, callback){
        var self = this;
		searchllist.title=name;
        DBHelper.insertWidgetTemplate(this.type,searchllist, function(d){
            if (parseInt(d, 10) > 0) {
                QS_ScreenerList[self.type].push({
                    id: parseInt(d),
                    title: name,
                    data: searchllist
                });
            }
            if (typeof callback == 'function') {
                callback(d);
            }
        });
    }
};

QS_SearchSave=function(type,callback){
	this.saveDBModule = new QS_SearchDB(type);
	this.callback={};
	$.extend(this.callback,callback);
};
QS_SearchSave.prototype={
	saveAs:function(data){
        var self=this;
		this._nameDialog("Save as", function(txt){
			if(self.callback.onSaveasBefore){
				self.callback.onSaveasBefore();
			}
			self.saveDBModule.addSearchItem(txt,data, function(d){
				d=$.trim(d);
				var flag=true;
				if (d==""||isNaN(d)||parseInt(d, 10) <= 0) {
					flag=false;
					Util.message(QS_Lang.screener.savedfailed);
				}
				else {
					Util.message(QS_Lang.screener.savedsuccess);
                    if(self.callback.onSaveasAfter){
                        self.callback.onSaveasAfter(flag,parseInt(d, 10),txt);
                    }
				}
			});
		});
    },
	getSearchData:function(id,callback){
		this.saveDBModule.getSearchData(id,callback);
	},
	list:function(data){//{type:"",trigger:"",title:"",container:"",hightLight:[],onClick:function(){},afterShow:function(moredialog){}}
        var self=this;
        this.saveDBModule.getSearchNameList(function(d){
            if(d=="error") return;
            if (!self.newSavedList || self.newSavedList == null) {
                self.moreDialog=new MoreDialog(data.container,data.title,{onClose:function(){self.callback.onClose();}});
				self.newSavedList=new QS_savedDataList(self.moreDialog.dom.find(".bd"),d,{selected:data.hightLight},{
					onClick:data.onClick
				});
            }
            else{
                self.moreDialog.setTitle(data.title);
                self.newSavedList.reBindEvent({onClick:data.onClick});
                self.newSavedList.rebind(d,data.hightLight);
            }
			var xy=data.trigger.position();
			self.moreDialog.setPositon(xy.top+24,xy.left-10,data.container);
			self.moreDialog.show();
			data.afterShow(self.moreDialog);
        });
    },
	save:function(id,data){
        var self=this;
		if(this.callback.onSaveBefore){
			this.callback.onSaveBefore(id);
		}
		this.saveDBModule.updateSearchItem(id, data, function(bool){
			if (!bool) {
				Util.message(QS_Lang.screener.updatedfailed);
			}
			else {
				Util.message(QS_Lang.screener.updatedsuccess);
			}
			if(self.callback.onSaveAfter){
				self.callback.onSaveAfter(bool,id);
			}
		});
    },
	remove:function(id,title){
        var name= this.saveDBModule.getSearchNameByID(id);
        var self=this;
        Util.confirm(String.format(QS_Lang.screener.deleteconfirm,name),function(bool){
                if (bool) {
					if(self.callback.onDeleteBefore){
						self.callback.onDeleteBefore(id);
					}
                    self._delete(id);
                }
        },{
            title:title||"Delete"
        })
	},
	getSearchNameByID:function(id){
		return this.saveDBModule.getSearchNameByID(id);
	},
	setDefault:function(id){
		if(this.callback.onDefaultBefore){
			this.callback.onDefaultBefore(id);
		}
        if (Terminal.getConfig("defaultCriterion") == id) {
            Util.message(QS_Lang.screener.alreadysetdefault);
        }
        else {
            var self=this;
            Terminal.setConfig({
                defaultCriterion: id
            }, function(d){
                if (d) {
                    Util.message(QS_Lang.screener.defaultsetsuccess);
                }
                else {
                    Util.message(QS_Lang.screener.defaultsetfaild);
                }
				if(self.callback.onDefaultAfter){
					self.callback.onDefaultAfter(d,id);
				}
            });
        }
    },
	_delete:function(id){
        var self=this;
        this.saveDBModule.deleteSearchItem(id,function(d){
            if (!d) {
                Util.message(QS_Lang.screener.deletedfailed);
            }
            else{
                if(Terminal.getConfig("defaultCriterion")==id){
                    Terminal.setConfig({
                        defaultCriterion: -1
                    });
                }
                Util.message(QS_Lang.screener.deletedsuccess);
            }
			if(self.callback.onDeleteAfter){
				self.callback.onDeleteAfter(d,id);
			}
        });
    },
	_nameDialog:function(title,callback){
        var self=this;
        Util.prompt(title, function(txt){
            if (callback) {
                callback($.trim(txt));
            }
        }, {
            validateMethod: function(txt){
                if ($.trim(txt) == "") {
                    Util.message(QS_Lang.screener.entername);
                    return false;
                }
                if (txt.length>30) {
                    Util.message(QS_Lang.screener.maxchar);
                    return false;
                }
                if (!QS_Validator.test($.trim(txt), 'name')) {
                    return false;
                }
                if (self.saveDBModule.existName($.trim(txt))){
                    Util.message(QS_Lang.screener.alreadyexistname);
                    return false;
                }
                return true;
            },
            label:"Name"
        });
    }
};

QS_savedDataList=function(container,data,cfg,callback){
	this.data=data;
	this.cb={};
	$.extend(this.cb,callback);
	this.container=container;
   	var EMPTY_FUNCTION=function(){};
    this.config = {
		search:false,
		title:true,//hover
		selected:[]
	};
	this.savedList={};
	$.extend(this.config,cfg);
    this._init();
};
QS_savedDataList.prototype = {
	_init: function(){
		this.el = $('<div class="qs-savedlist"></div>').appendTo(this.container);
		this.scrolldatalist = new Util.ScrollPanel(this.el, {
            showY: true,
            showX: false
        });
		this._createList();
	},
	rebind:function(data,selected){
		this.empty();
		this.data=data;
		this.config.selected=selected;
		this._createList();
	},
	reBindEvent:function(callback){
        $.extend(this.cb,callback);
    },
	_createList:function(){
		for(var i=0,l=this.data.length;i<l;i++){
			this._createATag(this.data[i]);
		}
		this.scrolldatalist.reSize(290, 180);
	},
	empty:function(){
		this.data=[];
		this.savedList={};
		this.el.empty();
	},
	_createATag:function(data){
		var aTag={};
		var self=this;
		aTag.data=data;
		aTag.dom=$('<a class="qs-savedunit'+($.inArray(data.id,this.config.selected)!=-1?' qs-savedunit-selected':'')+'" href="javascript:void(0);"><span>'+data.title+'</span></a>').appendTo(this.el);
		if(self.config.title){
			aTag.dom.attr('title',data.title);
		}
		aTag.active=function(e){self.cb.onClick(e,data);}
		aTag.hide=function(){aTag.dom.hide();}
		aTag.show=function(){aTag.dom.show();}
		aTag.dom.click(function(e){
            if(!self.cb.onClick){
                return ;
            }
            var target = $(e.target);
            switch(e.target.tagName.toLowerCase()){
                case 'span':
				    {
	                    aTag.active(e);
	                }
					break;
                case 'a':
				    {
                        aTag.active(e);
                    }
					break;
				default:
				    break;
            }
        }).hover(
            function(e){
                $(this).addClass('over');
            },
            function(e){
                $(this).removeClass('over');
            }
        );
		this.savedList[data.id]=aTag;
	},
	show:function(){
		this.el.show();
	},
	hide:function(){
		this.el.hide();
	}
};

var MoreDialog = function(ContainerObj,title,callback){
    var callback=$.extend({},callback);
    var el = $('<div class="qs-search-more-dlg"><div class="hd clearfix"><h3>'+title+'</h3><div class="qs-dlg-operate"><a href="javascript:void(0);" class="close"><em>x</em></a></div></div><div class="bd"></div></div>').appendTo(ContainerObj);
    el.find('.hd a.close').click(function(e){
        e.stopPropagation();
        if(typeof callback.onClose=='function'){
            callback.onClose();
        }
        Util.DelayRun('moreDialog_close', function(){el.hide()},100,this);
    });
    return {
        dom:el,
        setTitle:function(title){
            if ($.trim(title) != "") {
                el.find(".hd h3").text(title);
            }
        },
        setPositon:function(top,left,scale){
            if (top && left) {
                var allHeight = scale.height(), allWidth = scale.width();
                var width = el.width(), height = el.height();
                if (left + width > allWidth) {
                    left = allWidth - width-10;
                }
                el.css({left:(left-15)+"px",top:top+"px"});
            }
        },
        show:function(){
            el.show();
            ContainerObj.find('a').ellipsis(false,0);
        },
        hide:function(){el.hide();$('.qs-screener-operator .qs-screener-extend').removeClass('on');}
    };
};

var Search_buttonDialogCheckBox = function(ContainerObj, type,parent){ //type "checkbox" "radio"
    this.el = $('<div class="qs-search-chk-dlg"><div class="hd clearfix"><h3></h3><div class="qs-dlg-operate"><a href="javascript:void(0);" class="slt-all">Select All</a><span>|</span><a href="javascript:void(0);" class="clear">Clear</a><span>|</span><a href="javascript:void(0);" class="close">Close</a></div></div><div class="bd"><div class="btncontainer"></div></div></div>').appendTo(ContainerObj);
    this.rowData = null;
    this._timeOut=null;
    this._actTimeOut=null;
    this.trigger = null;
    this._type = type || 'checkbox';
    this.chkboxGroup = null;
    this.parent=parent;
    this.scrollPN = null;
    this.titleEl = null;
    this.init();
};
Search_buttonDialogCheckBox.prototype = {
    init: function(){
        var self = this;
        
        this.chkboxGroup = new Util.ButtonGroup(this.el.find('.btncontainer'), [], {
            onClick: function(v, item){
                if (item.isSelected) {
                    self.rowData.selected.push(v);
                }
                else {
                    var index = $.inArray(v, self.rowData.selected);
                    if (index != -1) {
                        self.rowData.selected.splice(index, 1);
                    }
                }
                self._setTriggerText(self.rowData.selected.length);
				if(self.parent&&self.parent.delaySearch){
					self.parent.delaySearch();
				}
            }
        }, {
            type: this._type,
            vertical: false,
            needTitle:true
        });
        
        this.scrollPN = new Util.ScrollPanel(this.el.find('.btncontainer'), {
            showY: true,
            showX: false
        });
        
        this.titleEl = this.el.find('.hd h3');
        
        this.el.find('.hd a.close').click(function(e){
            e.stopPropagation();
            self.hide();
        });
        
        this.el.find('.hd .slt-all').click(function(e){
            e.stopPropagation();
            self._selectAll(true);
            self._setTriggerText(self.rowData.selected.length);
			if(self.parent&&self.parent.delaySearch){
				self.parent.delaySearch();
			}
        });
        this.el.find('.hd .clear').click(function(e){
            e.stopPropagation();
            self._selectAll(false);
            self._setTriggerText(0);
			if(self.parent&&self.parent.delaySearch){
				self.parent.delaySearch();
			}
        });
        
    },
    setPosition:function(left,top){
        this.el.css({left:left,top:top});
    },
    show: function(){
        this.el.show();     
    },
    hide: function(){
        if (!this.mouseOver) {
            this.el.hide();
        }else{
            var self=this;
            if (this._timeOut) {
                clearTimeout(this._timeOut);
            }
            this._timeOut=setTimeout(function(){
                self.el.hide();
            },200);
        }
    },
    toggle: function(){
        this.el.toggle();
    },
    _setTriggerText: function(selected,type){
        if (selected > 0) {
            this.trigger[0].innerHTML = 'Selected ' + selected + ' item' + (selected > 1 ? 's' : '') + ' [Edit...]';
        }
        else {
            this.trigger[0].innerHTML = this.type=='dpl'?'Select...':'Select';
        }
    },
    _selectAll: function(isSelect){
        this.rowData.selected = [];
        for (var b in this.chkboxGroup.btns) {
            if (isSelect) {
                this.chkboxGroup.btns[b].select();
                this.rowData.selected.push(b);
            }
            else {
                this.chkboxGroup.btns[b].inverse();
            }
        }
    },
    setRow: function(rowData, trigger,type,screenerPosition){
			this.type=type;
            if(type=='dpl'){
                var xy=trigger.offset();
                this.setPosition(xy.left-screenerPosition.left+'px', xy.top-screenerPosition.top+18+'px');
                this.el.find('.hd').hide();
                if(!this.el.hasClass('qs-search-dropdown-dlg')){
                    this.el.addClass('qs-search-dropdown-dlg');
                }
                var self=this;
                this.mouseOver=true;
                this.el.unbind("mouseleave.dropdown").bind("mouseleave.dropdown",function(e){
                    self.hide();
                });
                this.el.unbind("mouseenter.dropdown").bind("mouseenter.dropdown",function(e){
                    if (self._timeOut) {
                        clearTimeout(self._timeOut);
                    }
                    self.show();
                });
                
            }else{
                this.mouseOver=false;
				//var scroll=Util.getScrollPosition();
                this.setPosition("50%","50%");
                this.el.unbind("mouseleave.dropdown").unbind("mouseenter.dropdown");
                this.el.find('.hd').show();
                if(this.el.hasClass('qs-search-dropdown-dlg')){
                    this.el.removeClass('qs-search-dropdown-dlg');
                }
            }
            this.titleEl.html(rowData.txt);
            this.rowData = rowData;
            this.trigger = trigger;
            this.chkboxGroup.bindData(rowData.selectable);
            for (var i = 0,l=rowData.selected.length;i <l; i++) {
                this.chkboxGroup.btns[rowData.selected[i]].select();
            }
            if (!this.mouseOver) {
                this.scrollPN.reSize(400, 270);
            }else{
                this.scrollPN.reSize(150, 205);
            }
            this._setTriggerText(rowData.selected.length);
       // }
    }
};
